﻿namespace ContosoUniversity.Controllers
{
    using System.Linq;
    using System.Web.Mvc;
    using ContosoUniversity.ViewModels;
    using NRepository.Core.Query;

    public class HomeController : Controller
    {
        private readonly IQueryRepository _QueryRepository;
     
        public HomeController(IQueryRepository queryRepository)
        {
            _QueryRepository = queryRepository;
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            //// Get EnrollmentDateGroup using query startegy (remove interceptor for EnrollmentDateGroup to enable this implementation).
            // var enrollmentProjections = _QueryRepository.GetEntities<EnrollmentDateGroup>(
            //    new CreateEnrollmentDateGroupQueryStrategy(_QueryRepository));

            // Using query interceptor
            var enrollmentProjections = _QueryRepository.GetEntities<EnrollmentDateGroup>();
            return View(enrollmentProjections.ToList());

            // Commenting out LINQ to show how to do the same thing in SQL.
            //IQueryable<EnrollmentDateGroup> = from student in db.Students
            //           group student by student.EnrollmentDate into dateGroup
            //           select new EnrollmentDateGroup()
            //           {
            //               EnrollmentDate = dateGroup.Key,
            //               StudentCount = dateGroup.Count()
            //           };

            //// SQL version of the above LINQ code.
            //string query = "SELECT EnrollmentDate, COUNT(*) AS StudentCount "
            //    + "FROM Person "
            //    + "WHERE Discriminator = 'Student' "
            //    + "GROUP BY EnrollmentDate";

            //var dbContext = _QueryRepository.ObjectContext as DbContext;
            //IEnumerable<EnrollmentDateGroup> data = dbContext.Database.SqlQuery<EnrollmentDateGroup>(query);

            //return View(data.ToList());
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        protected override void Dispose(bool disposing)
        {

        }
    }
}